package com.sqx.modules.errand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.cityInfo.entity.CityInfo;
import com.sqx.modules.cityInfo.service.CityInfoService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.dao.AdminDao;
import com.sqx.modules.errand.dao.UserInfoDao;
import com.sqx.modules.errand.entity.*;
import com.sqx.modules.errand.service.AdminService;
import com.sqx.modules.errand.vo.IndentVo;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.CashOut;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.WxRiderService;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.entity.SysUserRoleEntity;
import com.sqx.modules.sys.service.SysUserRoleService;
import com.sqx.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminDao, Indent> implements AdminService {

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private UserService userService;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private WxRiderService wxRiderService;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    public Result findDataCenter() {
        String format = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date());
        HashMap<String, Object> dataCenter = new HashMap<>();
        //总用户数
        int allCount = adminDao.findAllCount();
        //今日新增用户数
        int dayAddUser = adminDao.findDayAddUser(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        //本月新增用户数
        int monthAddUser = adminDao.findMonthAddUser(new SimpleDateFormat("yyyy-MM").format(new Date()));
        //本年新增用户数
        int yearAddUser = adminDao.findYearAddUser(new SimpleDateFormat("yyyy").format(new Date()));
        //今日收入
        BigDecimal dayIncome = adminDao.findDayIncome(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        //本月收入
        BigDecimal monthIncome = adminDao.findMonthIncome(new SimpleDateFormat("yyyy-MM").format(new Date()));
        //本年收入
        BigDecimal yearIncome = adminDao.findYearIncome(new SimpleDateFormat("yyyy").format(new Date()));
        //今日接单数量
        int indentCount = adminDao.findIndentCount(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        dataCenter.put("allCount", allCount);
        dataCenter.put("dayAddUser", dayAddUser);
        dataCenter.put("monthAddUser", monthAddUser);
        dataCenter.put("yearAddUser", yearAddUser);
        dataCenter.put("dayIncome", dayIncome);
        dataCenter.put("monthIncome", monthIncome);
        dataCenter.put("yearIncome", yearIncome);
        dataCenter.put("indentCount", indentCount);
        return Result.success().put("data", dataCenter);
    }

    @Override
    public Result taskAnalysis(String dateType, String date, Integer page, Integer limit, String indentState, Long cityId) {
        HashMap<String,Object> hashMap = new HashMap<>();
        //发单总金额
        BigDecimal billMoney = adminDao.billMoney(dateType, date,cityId);
        //接单总金额
        BigDecimal receivingMoney = adminDao.receivingMoney(dateType, date,cityId);

        //发单数量
        int billCount = adminDao.billCount(dateType, date,cityId);
        //接单数量
        int reveivingCount = adminDao.reveivingCount(dateType, date,cityId);
        //任务收入分析
        Page<Indent> pages = new Page<>(page, limit);
        PageUtils taskAnalysisMoney = new PageUtils(baseMapper.taskAnalysisMoney(pages, dateType, date, indentState,cityId));
        hashMap.put("billMoney", billMoney);
        hashMap.put("receivingMoney", receivingMoney);
        hashMap.put("billCount", billCount);
        hashMap.put("reveivingCount", reveivingCount);
        hashMap.put("taskAnalysisMoney", taskAnalysisMoney);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result findUserMessage(Long userId) {
        String format = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date());
        HashMap<String, Object> hashMap = new HashMap<>();
        //本月接单数量
        int monthAcceptCount = adminDao.monthAcceptCount(userId, format);
        //本月派单数量
        int monthGrantCount = adminDao.monthGrantCount(userId, format);
        //本月充值金额
        BigDecimal monthTopUpMoney = adminDao.monthTopUpMoney(userId, format);
        //本月提现金额
        BigDecimal monthWithdrawMoney = adminDao.monthWithdrawMoney(userId, format);
        //用户基本信息
        int InviteCount = 0;
        UserEntity userMessage = userService.getById(userId);
        if (userMessage != null) {
            adminDao.InviteCount(userMessage.getInvitationCode(), format);
        }
        //用户余额
        BigDecimal userMoney = adminDao.getUserMoney(userId);
        //师傅收益
        BigDecimal riderMoneySum = adminDao.riderMoneySum(userId);
        hashMap.put("monthAcceptCount", monthAcceptCount);
        hashMap.put("monthGrantCount", monthGrantCount);
        hashMap.put("monthTopUpMoney", monthTopUpMoney);
        hashMap.put("monthWithdrawMoney", monthWithdrawMoney);
        hashMap.put("InviteCount", InviteCount);
        hashMap.put("userMessage", userMessage);
        hashMap.put("riderMoneySum", riderMoneySum);
        hashMap.put("userMoney", userMoney);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result findUserAddIndent(Long userId, Integer page, Integer limit) {
        Page<IndentVo> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findUserAddIndent(pages, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findUserReceivingIndent(Long userId, Integer page, Integer limit) {
        Page<Indent> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findUserReceivingIndent(pages, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findTopUpMoney(Integer page, Integer limit, PayDetails payDetails, String startTime, String endTime) {
        Page<PayDetails> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findTopUpMoney(pages,payDetails, startTime, endTime));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findWithdrawMoney(Long userId, Integer page, Integer limit) {
        Page<CashOut> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findWithdrawMoney(pages, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public IPage<IndentVo> findAllIndent(Integer page, Integer limit, String date, String dateType, IndentVo indentVo) {
        Page<IndentVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        SysUserEntity sysUserEntity = sysUserService.getLoginUser();
        //是否是代理角色
        int count = sysUserRoleService.count(new QueryWrapper<SysUserRoleEntity>().eq("role_id", 5).eq("user_id", sysUserEntity.getUserId()));
        if (count > 0) {
            CityInfo cityInfo = cityInfoService.getOne(new QueryWrapper<CityInfo>().eq("agent_user_id", sysUserEntity.getUserId()));
            //如果没有代理城市
            if (cityInfo != null) {
                indentVo.setCityId(cityInfo.getId());
            } else {
                return new Page<>();
            }
        }
        return baseMapper.findAllIndent(pages, date, dateType, indentVo);
    }

    @Override
    public Result findCertification(Long userId) {
        UserEntity certification = adminDao.findCertification(userId);
        return Result.success().put("data", certification);
    }

    @Override
    public Result updateState(Long userId, Integer status) {
        int i = adminDao.updateState(userId, status);
        return Result.success();
    }

    @Override
    public Result findAllUser(Integer page, Integer limit, String phone, Integer userType, String platform, String nickName, String invitationCode,
                              Integer isAgent, Integer onLineFlag,String inviterCode) {
        Page<Indent> pages = new Page<>(page, limit);
        return Result.success().put("data", new PageUtils(baseMapper.findAllUser(pages, phone, userType, platform, nickName,
                invitationCode, isAgent, onLineFlag,inviterCode)));
    }

    @Override
    public Result checkCertification(Long userId, String checkCertification, String checkCertificationMessage) {
        boolean flag;
        UserEntity userEntity = userService.selectUserById(userId);
        if ("2".equals(checkCertification)) {
            PayDetails payDetails = payDetailsDao.selectByOrderId(userEntity.getCheckNumber());
            if (payDetails != null) {
                if (payDetails.getClassify().equals(4) || payDetails.getClassify().equals(5)) {
                    flag = aliPayController.aliRefund(payDetails);
                } else {
                    flag = wxRiderService.wxRefund(payDetails);
                }
                if (!flag) {
                    return Result.error("退款失败！");
                }
                //退保证金的记录
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setUserId(userId);
                userMoneyDetails.setUserType(2);
                userMoneyDetails.setTitle("退还保证金");
                userMoneyDetails.setContent("实名认证审核未通过，保证金：" + payDetails.getMoney() + "元已退还至原支付途径");
                userMoneyDetails.setType(1);
                userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
                userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss").format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
                userMoneyDetails.setClassify(1);
                userMoneyDetails.setType(2);
                userMoneyDetailsService.save(userMoneyDetails);
            }
            userEntity.setCashDeposit(BigDecimal.valueOf(0));
        } else {
            userEntity.setIsEnableReward(1);
            int value = Integer.parseInt(commonInfoService.findOne(345).getValue());
            if (value > 0) {
                //当前时间加上天数
                userEntity.setCloseRewardTime(LocalDateTime.now().plusDays(value));
            } else {
                userEntity.setCloseRewardTime(LocalDateTime.now());
            }
            userEntity.setUserType(2);
        }
        CityInfo cityInfo = cityInfoService.getOne(new QueryWrapper<CityInfo>().eq("city_name", userEntity.getCity()));
        if (cityInfo == null) {
            return Result.error("所选常驻区域不存在");
        }
        userEntity.setRate(cityInfo.getRiderRate().toString());
        userEntity.setCheckCertification(checkCertification);
        userEntity.setCheckCertificationMessage(checkCertificationMessage);
        userDao.updateById(userEntity);
        return Result.success();
    }

    @Override
    public Result findAllCertification(Integer page, Integer limit, String nickName, String phone, String checkCertification) {
        Page<UserEntity> pages = new Page<>(page, limit);
        return Result.success().put("data", new PageUtils(baseMapper.findAllCertification(pages, nickName, phone, checkCertification)));
    }

    /*@Override
    public Result findAllAppeal(Complaint complaint) {
        Page<Complaint> pages=new Page<>(complaint.getPage(),complaint.getLimit());
        PageUtils pageUtils = new PageUtils(baseMapper.findAllAppeal(pages,complaint.getRiderUserId(),  complaint.getAppealMessage(), complaint.getIndentNumber(), complaint.getComplaintState()));
        return Result.success().put("data", pageUtils);
    }*/


    @Override
    public Result updateIndentState(String indentNumber, String indentState) {
        int i = adminDao.updateIndentState(indentNumber, indentState);
        return Result.success();
    }

    @Override
    public Result updateNewRedPacket(double redPacketAmount, Integer count) {

        return null;
    }

    @Override
    public Result IndentCenter(Integer page, Integer limit, String indentType, String indentNumber, String indentState, String phone, String date, String dateType, String startTime, String endTime, String parentName, String parentParentName) {
        Page<Indent> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(baseMapper.IndentCenter(pages, indentType, indentNumber, indentState, phone, date, dateType, startTime, endTime, parentName, parentParentName));

        return Result.success().put("data", pageUtils);
    }


    @Override
    public Result adminSoldOutIndent(String indentNumber) {
        adminDao.adminSoldOutIndent(indentNumber);
        return Result.success();
    }

    @Override
    public Result adminTrainingCenter(Integer page, Integer limit, String title, Integer type) {
        Page<Indent> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(baseMapper.adminTrainingCenter(pages, title, type));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result updateAdminTrainingCenter(TrainingCenter trainingCenter) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        adminDao.updateAdminTrainingCenter(trainingCenter.getTrainingId(), trainingCenter.getTitle(), trainingCenter.getMessage(), trainingCenter.getDeleteFlag(), format, trainingCenter.getType());
        return Result.success();
    }

    @Override
    public Result addAdminTrainingCenter(TrainingCenter trainingCenter) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        adminDao.addAdminTrainingCenter(trainingCenter.getTitle(), trainingCenter.getMessage(), trainingCenter.getDeleteFlag(), format, trainingCenter.getType());
        return Result.success();
    }

    @Override
    public Result findUserMoneyDetails(Long userId, Integer page, Integer limit) {
        Page<UserMoneyDetails> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findUserMoneyDetails(pages, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findplatformMoney(String dateType, String date) {
        HashMap hashMap = new HashMap();
        BigDecimal indentMoney = adminDao.billMoney(dateType, date, null);
        BigDecimal riderMoney = adminDao.riderMoney(dateType, date);
        BigDecimal platformMoney = adminDao.platformMoney(dateType, date);
        hashMap.put("indentMoney", indentMoney);
        hashMap.put("riderMoney", riderMoney);
        hashMap.put("platformMoney", platformMoney);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result findIncome(Long userId, String date, String dateType, Integer page, Integer limit) {
        HashMap hashMap = new HashMap();
        //收益统计
        BigDecimal incomeday = userInfoDao.findAdminIncomeday(userId, date, dateType);
        //接单数量
        int indentCount = userInfoDao.findAdminIndentCount(userId, date, dateType);
        //接单详情
        Page<Indent> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(userInfoDao.selectIndentById(pages, userId, date, dateType));

        hashMap.put("incomeday", incomeday);
        hashMap.put("indentCount", indentCount);
        hashMap.put("pageUtils", pageUtils);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectUserFeedback(String userEmail, Integer page, Integer limit, Integer feedType) {
        Page<Feedback> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(userInfoDao.selectUserFeedback(pages, userEmail, feedType));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectUserStatistics(String date, String dateType) {
        HashMap hashMap = new HashMap();
        //累计用户
        int allUser = userInfoDao.selectAllUser(date, dateType);
        //普通用户
        int userCount1 = userInfoDao.selectUserCount(date, dateType, 1);
        //师傅用户
        int userCount2 = userInfoDao.selectUserCount(date, dateType, 2);
        //手机号用户
        int phoneUserCount = userInfoDao.selectPhoneUserCount(date, dateType);
        hashMap.put("allUser", allUser);
        hashMap.put("userCount1", userCount1);
        hashMap.put("userCount2", userCount2);
        hashMap.put("phoneUserCount", phoneUserCount);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result TrainingCenter(Long id) {
        TrainingCenter trainingCenter = userInfoDao.TrainingCenter(id);
        return Result.success().put("data", trainingCenter);
    }

    @Override
    public Result selectOrderByStatus(String date, String dateType, Long cityId) {
        HashMap<String, Integer> hashMap = new HashMap<>();
//        订单状态 0待接单 1已接单 2进行中 3待支付 4已完成 5已取消
        int allCount = adminDao.selectOrderByStatus(date, dateType, null, cityId);
        int daiJieDan = adminDao.selectOrderByStatus(date, dateType, 0, cityId);
        int yiJieiDan = adminDao.selectOrderByStatus(date, dateType, 1, cityId);
        int jinXingZhong = adminDao.selectOrderByStatus(date, dateType, 2, cityId);
        int daiZhiFu = adminDao.selectOrderByStatus(date, dateType, 3, cityId);
        int yiWanChen = adminDao.selectOrderByStatus(date, dateType, 4, cityId);
        int yiQuXiao = adminDao.selectOrderByStatus(date, dateType, 5, cityId);

        hashMap.put("daiJieDan", daiJieDan);
        hashMap.put("yiJieiDan", yiJieiDan);
        hashMap.put("jinXingZhong", jinXingZhong);
        hashMap.put("daiZhiFu", daiZhiFu);
        hashMap.put("yiWanChen", yiWanChen);
        hashMap.put("yiQuXiao", yiQuXiao);
        hashMap.put("allCount", allCount);

        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectCashDeposit(String phone, Integer type, Integer page, Integer limit, Long userId) {
        Page<UserMoneyDetails> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(adminDao.selectCashDeposit(pages, phone, type, userId));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public IPage<Indent> findWaitIndent(Long userId, Integer page, Integer limit) {
        Page<Indent> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.findWaitIndent(pages, userId);
    }

}
